import Taro from "@tarojs/taro";
import GlobalData from "../global";
const CONFIG = require('../config')

export interface Options {
    method : 'POST' | 'GET' | 'DELETE';
    data? : any;
}

export interface Result {
    success : boolean;
    code? : number;
    data? : any;
    msg : string;
}

class Http {
    private sending:boolean = false;

    async post(url: string, data?: any)  : Promise<Result>{
        if(this.sending) {
            throw '请等待'
        }
        this.sending = true
        let result = await Http.post(url, data)
        this.sending = false
        return result
    }

    static post(url: string, data?: any) : Promise<Result> {
        let options:Options = {
            method : 'POST'
        }
        if(data) {
            options.data = data
        }

        return Http.send(url, options)
    }

    async get(url: string, data?: any) : Promise<Result>{
        if(this.sending) {
            throw '请等待'
        }
        this.sending = true
        let result = await Http.get(url, data)
        this.sending = false
        return result
    }

    static get(url: string, data?: any) : Promise<Result>{
        let options:Options = {
            method : 'GET'
        }

        if(data) {
            options.data = data
        }

        return Http.send(url, options)
    }

    async delete(url: string, data?: any) : Promise<Result>{
        if(this.sending) {
            throw '请等待'
        }
        this.sending = true
        let result = await Http.delete(url, data)
        this.sending = false
        return result
    }

    static delete(url: string, data?: any) : Promise<Result>{
        let options:Options = {
            method : 'DELETE'
        }

        if(data) {
            options.data = data
        }

        return Http.send(url, options)
    }

    static async send(url: string, options: Options) : Promise<Result>{
        let result:Result = {
            msg : '',
            success : false
        }

        try {
            let header:{[key : string] : string | number} = {
                'Content-type' : 'application/json',
                'client-source' : GlobalData.clientType
            }

            if(process.env.access_token) {
                header.Authorization = process.env.access_token
            }
            
            let response = await Taro.request({
                url : CONFIG.API_URL + url,
                ...options,
                header,
                dataType : 'json'
            })


            let data = response.data
            if(data) {
                result.code = data.statusCode
                result.data = data.data
                result.msg = data.msg || data.message || '请求信息失败，请检查网络'
                result.success = data.statusCode == 200 || data.statusCode == 0
            }
            
        } catch (error) {
            result.msg = error.message
        }

        return result
    }

}

export default Http